package com.bs.resa.web;

import com.bs.resa.common.FastDFSClient;
import com.bs.resa.pojo.File;
import com.bs.resa.service.FileServive;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lin
 * @date 2019/4/1 22:08
 */
@Controller
public class FileUploadController {
    protected Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

    @Value("${fastdfs_setting.IMAGE_SERVER_URL}")
    private String ip;
    @Autowired
    FileServive fileServive;
    private static Map<String,Object > mapType=new HashMap<>();
    static {
        mapType.put("doc","<i class='fa fa-file-word-o'></i>");
        mapType.put("docx","<i class='fa fa-file-word-o'></i>");
        mapType.put("txt","<i class='fa fa-file-word-o'></i>");
        mapType.put("pdf","<i class='fa fa-file-pdf-o'></i>");
        mapType.put("jpg","<i class='fa fa-picture-o'></i>");
        mapType.put("jpeg","<i class='fa fa-picture-o'></i>");
        mapType.put("png","<i class='fa fa-picture-o'></i>");
        mapType.put("bmp","<i class='fa fa-picture-o'></i>");
        mapType.put("git","<i class='fa fa-picture-o'></i>");
        mapType.put("other","<i class='fa fa-file-word-o'></i>");

    }

    @ApiOperation(value = "项目文件上传",notes = "POST")
    @ResponseBody
    @RequestMapping(value = "project/fileUpload/{type}/{pid}.do",method = RequestMethod.POST)
    public Object projectFileUpload(@PathVariable("type") String type,
                                    @PathVariable("pid") String pid,
                                    @RequestParam("file") MultipartFile[] files){
        System.out.println("fileUpload..");
        String extName = ""; // 文件扩展名
        String originalFilename = "";// 上传文件名
        String url=""; //访问图片的url地址
        for(MultipartFile file:files){
            originalFilename = file.getOriginalFilename();
            extName = originalFilename.indexOf(".") != -1
                    ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length())
                    : null;
            try {
                FastDFSClient fastDFSClient = new FastDFSClient("client.conf");

                String url1 = fastDFSClient.uploadFile(file.getBytes(), extName);
                System.out.println("上传路径："+url1);
                url =ip+"/"+(url1.substring(7));
                //新增文件表
                File file1=new File();
                file1.setFtitle(originalFilename);
                file1.setDescription("访问路径："+url);
                file1.setFpath(url);
                file1.setSize(getNetFileSizeDescription(file.getSize()));
                String icon="";
                if(!mapType.containsKey(extName)){
                    file1.setFicon(String.valueOf(mapType.get("other")));
                }else{
                    file1.setFicon(String.valueOf(mapType.get(extName)));
                }

                boolean flag=fileServive.insertFile(type,pid,file1);

                System.out.println(url);
                resultMap.put("code",200);
                resultMap.put("message","文件上传成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultMap ;
    }

    @ApiOperation(value = "查询项目文件",notes = "POST")
    @ResponseBody
    @RequestMapping(value = "project/queryFileList/{pid}.do",method = RequestMethod.POST)
    public Object queryProjectFiles(@PathVariable("pid") String pid){
        try {
            List<File> fileList=fileServive.queryProjectFiles(pid);
            resultMap.put("code",200);
            resultMap.put("message","查询项目文件成功");
            resultMap.put("data",fileList);

        }catch (Exception e){
            resultMap.put("code",500);
            resultMap.put("message",e.getMessage());
            resultMap.put("data",null);
        }

        return resultMap;
    }

    @ApiOperation(value = "文件下载")
    @RequestMapping(value="/download/{fid}.do")
    public ResponseEntity<byte[]> down(HttpServletRequest request,@PathVariable("fid")String fid)throws Exception{
        File fileinfo=fileServive.queryFileById(fid);
        //下载路径
        FastDFSClient fast=new FastDFSClient("client.conf");
        String path=fileinfo.getFpath().substring(fileinfo.getFpath().indexOf("M00"));
        System.out.println("path:"+path);
        byte[] b=fast.download(path);
//        String paths="C:/"+fileinfo.getFtitle();
        String paths=request.getServletContext().getRealPath("/downFile/");
        IOUtils.write(b, new FileOutputStream(paths));
        java.io.File file=new java.io.File(paths);
        System.out.println("byte:"+b);
        //        java.io.File file=new java.io.File();
        HttpHeaders headers=new HttpHeaders();

        //下载显示的文件名，解决中文名称乱码问题
        String downloadfilename=new String(fileinfo.getFtitle().getBytes("UTF-8"),"iso-8859-1");

        //通知浏览器以attachment (下载方式)打开图片
        headers.setContentDispositionFormData("attachment", downloadfilename);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

    @ApiOperation(value = "删除文件")
    @RequestMapping(value="/delete/{fid}.do" )
    @ResponseBody
//    @RequiresPermissions(value = "/delete/{fid}.do")
    public Object delete(@PathVariable("fid")String fid) throws Exception {
        FastDFSClient fast=new FastDFSClient("client.conf");
        File fileinfo=fileServive.queryFileById(fid);
        String path=fileinfo.getFpath().substring(fileinfo.getFpath().indexOf("M00"));
       int i= fast.delete_file(path);
       if(i==0){
           if(fileServive.deleteFileById(fid)==1)
           resultMap.put("code",200);
       }else{
           resultMap.put("code",500);
       }

       return resultMap;
    }

    public static String getNetFileSizeDescription(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.0");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        }
        else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        }
        else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        }
        else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            }
            else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }
}
